package com.baizhi.controller;


import com.baizhi.service.ArticleService;
import com.baizhi.entity.Article;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @RequestMapping("getAll")
    @ResponseBody
    public Map getAll(@RequestParam(defaultValue = "1") Integer page,
                      @RequestParam(defaultValue = "3") Integer limit, Article article){
        HashMap map = new HashMap();
        try {
            PageInfo<Article> pageInfo = articleService.findAll(page, limit, article);
            List<Article> articles = pageInfo.getList();
            int count = (int) pageInfo.getTotal();
            map.put("data", articles);
            map.put("code", 0);
            map.put("count", count);
            return map;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("getOne")
    @ResponseBody
    public Article getArticle(Article article){
        try {
            return articleService.fidnArticlByFields(article);
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("addOne")
    @ResponseBody
    public Boolean addArticle(Article article){
        try {
            articleService.addArticle(article);
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("delById")
    @ResponseBody
    public Boolean deleteArticleById(Article article){
        try {
            articleService.removeArticleById(article.getArticleId());
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("delBulk")
    @ResponseBody
    public Boolean deleteMultiple(Integer[] ids){
        try {
            articleService.removeMultiple(ids);
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("update")
    @ResponseBody
    public Boolean updateArticle(Article article){
        try {
            articleService.renovateArticle(article);
            return true;
        } catch (RuntimeException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}



